// ============================================================================
// E2E 测试全局清理
// ============================================================================

import { FullConfig } from '@playwright/test'
import path from 'path'
import fs from 'fs'

async function globalTeardown(config: FullConfig) {
  console.log('🧹 开始E2E测试全局清理...')
  
  try {
    // 清理测试数据文件
    const testDataPath = path.join(__dirname, 'test-data.json')
    if (fs.existsSync(testDataPath)) {
      fs.unlinkSync(testDataPath)
      console.log('✅ 测试数据文件已清理')
    }
    
    // 清理临时文件
    await cleanupTempFiles()
    
    // 生成测试报告摘要
    await generateTestSummary()
    
    console.log('✅ E2E测试全局清理完成')
  } catch (error) {
    console.error('❌ 全局清理时出错:', error)
  }
}

/**
 * 清理临时文件
 */
async function cleanupTempFiles() {
  console.log('🗑️ 清理临时文件...')
  
  const tempDirs = [
    path.join(__dirname, '..', 'temp'),
    path.join(__dirname, '..', '.tmp')
  ]
  
  for (const dir of tempDirs) {
    if (fs.existsSync(dir)) {
      try {
        fs.rmSync(dir, { recursive: true, force: true })
        console.log(`✅ 已清理临时目录: ${dir}`)
      } catch (error) {
        console.warn(`⚠️ 清理临时目录失败: ${dir}`, error)
      }
    }
  }
}

/**
 * 生成测试报告摘要
 */
async function generateTestSummary() {
  console.log('📊 生成测试报告摘要...')
  
  try {
    const resultsPath = path.join(__dirname, '..', 'test-results', 'results.json')
    
    if (fs.existsSync(resultsPath)) {
      const results = JSON.parse(fs.readFileSync(resultsPath, 'utf-8'))
      
      const summary = {
        timestamp: new Date().toISOString(),
        total: results.stats?.total || 0,
        passed: results.stats?.passed || 0,
        failed: results.stats?.failed || 0,
        skipped: results.stats?.skipped || 0,
        duration: results.stats?.duration || 0,
        projects: results.suites?.map((suite: any) => ({
          name: suite.title,
          tests: suite.specs?.length || 0,
          passed: suite.specs?.filter((spec: any) => spec.ok).length || 0,
          failed: suite.specs?.filter((spec: any) => !spec.ok).length || 0
        })) || []
      }
      
      const summaryPath = path.join(__dirname, '..', 'test-results', 'summary.json')
      fs.writeFileSync(summaryPath, JSON.stringify(summary, null, 2))
      
      // 输出摘要到控制台
      console.log('\n📋 测试摘要:')
      console.log(`   总计: ${summary.total}`)
      console.log(`   通过: ${summary.passed}`)
      console.log(`   失败: ${summary.failed}`)
      console.log(`   跳过: ${summary.skipped}`)
      console.log(`   耗时: ${(summary.duration / 1000).toFixed(2)}s`)
      
      if (summary.projects.length > 0) {
        console.log('\n📱 项目详情:')
        summary.projects.forEach(project => {
          console.log(`   ${project.name}: ${project.passed}/${project.tests} 通过`)
        })
      }
      
      console.log('✅ 测试报告摘要已生成')
    } else {
      console.warn('⚠️ 未找到测试结果文件')
    }
  } catch (error) {
    console.error('❌ 生成测试报告摘要失败:', error)
  }
}

export default globalTeardown
